<template>
<div>
  <el-button type="warning" @click="changeUser"
             size="mini"
             style="margin-left: 800px;"
             plain>切换用户</el-button> 当前用户：{{this.queryForm.userId}}
      <el-row type="flex"  class="row-bg" justify="center">
          <div  style="width: 400px;height: 300px;">
            <span style="color: #42c025;font-weight: bold;font-size: 24px;">卖出股票</span>
            <el-form :model="formInline" style="margin-top: 25px;" class="demo-form-inline">
              <el-form-item label="证劵代码">
                <el-autocomplete
                    class="inline-input"
                    v-model="formInline.entrustStockCode"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入内容"
                    @select="handleSelect"
                    clearable
                ></el-autocomplete>
              </el-form-item>
              <el-form-item  label="证劵名称">
                <el-input  style="width: 200px;" v-model="formInline.entrustBankName" placeholder="证劵名称"></el-input>
              </el-form-item>
              <el-form-item label="可卖(股)">
                <el-input style="width: 200px;" v-model="maxCount" placeholder="可买（股）" readonly></el-input>
              </el-form-item>
              <el-form-item label="价格">
                <el-input-number v-model="formInline.entrustPrice"  controls-position="right" :min="0" ></el-input-number>
              </el-form-item>
              <el-form-item label="卖出(股)">
                <el-input-number v-model="formInline.entrustNum" controls-position="right"  :min="0" style="margin-right: 27px;"></el-input-number>
              </el-form-item>
              <el-form-item>
                <el-button type="success" size="medium" @click="saveEntrust" >卖出</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div style="width: 300px;height: 300px;">
    <span style="color: red;font-weight: bold;font-size: 20px;">行情时间:<br>
              {{ nowTime }}</span>
            <el-table
                :data="sellTableData"
                style="width: 80%">
              <el-table-column
                  prop="entrustStockCode"
                  label="编号"
                  width="80">
              </el-table-column>
              <el-table-column
                  prop="entrustPrice"
                  label="售出价格"
                  width="80">
              </el-table-column>
              <el-table-column
                  prop="entrustNum"
                  width="80"
                  label="售出数量">
              </el-table-column>
            </el-table>
            <br>
            <br>
            <el-table
                :data="buyTableData"
                style="width: 80%">
              <el-table-column
                  prop="entrustStockCode"
                  label="编号"
                  width="80">
              </el-table-column>
              <el-table-column
                  prop="entrustPrice"
                  label="购入价格"
                  width="80">
              </el-table-column>
              <el-table-column
                  prop="entrustNum"
                  width="80"
                  label="购入数量">
              </el-table-column>
            </el-table>
          </div>
      </el-row>
     <div align="center" style="margin-top: 120px;">
       <el-divider style="color: green"></el-divider>
       可用资金：<span style="color: red ;margin-right: 800px;"> {{comount}}</span>
       <el-table
           :data="tableData"
           style="width: 100%">
         <el-table-column
             prop="value"
             label="股票代码"
             width="180">
         </el-table-column>
         <el-table-column
             prop="stockName"
             label="股票名称"
             width="180">
         </el-table-column>
         <el-table-column
             prop="userStockCount"
             label="股票数量"
             width="180">
         </el-table-column>
         <el-table-column
             prop="stockAllPrice"
             label="总投入"
             width="180">
         </el-table-column>
         <el-table-column
             prop="stockPrice"
             label="成本"
             width="180">
         </el-table-column>
       </el-table>
<!--       分页-->
       <el-pagination
           background
           :page-size="this.queryForm.pageSize"
           :current-page="this.queryForm.pageSize"
           @current-change="toNewPage"
           layout="prev, pager, next"
           :total="total">
       </el-pagination>
     </div>
</div>
</template>

<script>
import VueWS from "vue-websocket";
export default {
  name: "BuyOutView",
  mixins: [VueWS],
  data(){
    return{
      nowTime: null,
      buyTableData: [],
      sellTableData: [],
      maxCount:null,
      formInline:{},
      comount:null,
      tableData:[],
      total:0,
      queryForm:{
        pageNum:1,
        pageSize:3,
        userId:4,
      },
      restaurants:[],
    }
  },
  methods:{
    //切换用户
    changeUser(){
      if(this.queryForm.userId==1){
        this.queryForm.userId=4;
      }else if(this.queryForm.userId==4){
        this.queryForm.userId=1;
      }
      console.log(this.queryForm.userId);
      this.getStockByList();
      this.getUserMoney();
    },
    //输入建议
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    //选择建议的股票号后，回显其名称和数量
    handleSelect(item) {
      this.formInline.entrustBankName=item.stockName;
      this.maxCount=item.userStockCount;
      console.log(item);
    },
    //添加委托（卖出）
    saveEntrust(){
      this.formInline.entrustDirection='卖出';
      this.formInline.haveId=this.queryForm.userId;
      this.axios.post("http://localhost:8182/stock/saveEntrust",this.formInline).then(r=>{
        if(r.data.code==200){
          this.$message.success(r.data.data);
          this.formInline={};
          window.setTimeout(function (){
            window.location.reload();
          },500)
        }
      })
    },
    //分页
    toNewPage(newPage){
      this.queryForm.pageNum=newPage;
      this.getStockByList();
    },
    //获得用户的股票列表(附带数量)，以及建议的列表
    getStockByList(){
      this.axios.post("http://localhost:8182/stock/getStockByList",this.queryForm).then(r=>{
        this.tableData=r.data.data.list;
        this.total=r.data.data.total;
        this.restaurants=r.data.data.list
      })
    },
    //获得用户的可用资金
    getUserMoney(){
      this.axios.get("http://localhost:8182/stock/getUserMoney?userId="+this.queryForm.userId).then(r=>{
        this.comount=r.data.data;
      })
    },
    connectWebSocket() {
      // 创建 WebSocket 连接
      this.websocket = new WebSocket("ws://localhost:8182/api/pushMessage2/" + this.queryForm.userId);

      // 监听 WebSocket 连接打开事件
      this.websocket.onopen = () => {
        console.log('WebSocket 连接已打开');
      };

      // 监听 WebSocket 接收消息事件
      this.websocket.onmessage = (event) => {
        if (event.data !== "连接成功") {
          let data = JSON.parse(event.data);
          console.log('接收到消息：', data);
          this.buyTableData = data.buyEntrustList;
          this.sellTableData = data.sellEntrustList;
          this.nowTime = data.time;
        }
      };

      // 监听 WebSocket 关闭事件
      this.websocket.onclose = () => {
        console.log('WebSocket 连接已关闭');
      };

      // 监听 WebSocket 错误事件
      this.websocket.onerror = (error) => {
        console.error('WebSocket 出现错误:', error);
      };
    },
  },
  mounted() {
    // 在 mounted 钩子中连接 WebSocket
    this.connectWebSocket();
    this.getStockByList();
    this.getUserMoney();
    // this.getStockList();
  },
  beforeDestroy() {
    // 在组件销毁之前关闭 WebSocket 连接
    if (this.websocket) {
      this.websocket.close();
    }
  },
}
</script>

<style scoped>

</style>